package com.lichhao.common.service;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.LinkedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.lichhao.common.dao.BaseDao;
import com.lichhao.common.model.BaseBean;
import com.lichhao.common.util.QueryParam;
import com.lichhao.common.util.json.JackJson;

public abstract class BaseService<T extends BaseBean> {

	protected BaseDao<T> baseDao;

	public abstract void setBaseDao(BaseDao<T> baseDao);

	private Class<T> beanClass;

	public BaseService() {
		Type genType = getClass().getGenericSuperclass();
		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
		beanClass = (Class) params[0];
	}

	public Class<T> getBeanClass() {
		return this.beanClass;
	}

	public void addRecord(T bean) {
		baseDao.addRecord(bean);
	}

	public void deleteRecord(T bean) {
		baseDao.deleteRecord(bean);
	}

	public T findRecord(T bean) {
		return baseDao.findRecord(bean);
	}

	public void updateRecord(T bean) {
		baseDao.updateRecord(bean);
	}

	public String queryList(QueryParam queryParam) {

		List<T> listTotal = baseDao.getMongoTemplate().findAll(getBeanClass());
		int page = queryParam.getPageNumber();
		int total = listTotal.size();
		Map map = new LinkedMap(3);
		map.put("page", page);
		map.put("total", total);

		Query query = new Query();
		if (!StringUtils.isEmpty(queryParam.getQuery())) {
			query.addCriteria(Criteria.where(queryParam.getQtype()).is(
					queryParam.getQuery()));
		}
		query.skip(queryParam.getSkip()).limit(queryParam.getLimit()).sort()
				.on(queryParam.getSortname(), queryParam.getSortorder());

		List<T> list = baseDao.getMongoTemplate().find(query, getBeanClass());
		List<Map<String, Object>> mapList = new LinkedList<Map<String, Object>>();
		for (T bean : list) {
			mapList.add(bean.toMap());
		}
		map.put("rows", mapList);

		String json = JackJson.fromObjectToJson(map);

		return json;
	}
}
